import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { NzUploadFile } from 'ng-zorro-antd/upload/interface';
import { firstValueFrom } from 'rxjs';
import { MessageService } from 'src/app/service/message.service';
import { UploadService } from 'src/app/service/upload.service';
import { FILE_TYPE } from './file-type';

interface UploadedFileData{
  fileId: string,
  fileName: string,
  groupId: 'string',
  filePath: string,
  path: string,
  size: string,
  bytes: string,
  createTime: string
}

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.scss']
})
export class FileUploadComponent implements OnInit, OnChanges {

  @Input() setId = ''

  @Input() uploadAvailable = true; // 上传按钮 是否可用
  @Input() deleteAvailable = true;

  @Input() required = 'false'

  @Input() mediaType: Array<string> = ['jpg', 'png', 'jpeg', 'gif','pdf','bmp']; // 支持的 文件扩展名
  @Input() fileSize: number = 10240; // 文件大小 kb
  @Input() typeIds: any;//传入的表单得typeId,以此判断接口
  @Input() fieldKey: string = ''; // 提供绑定name字段
  @Input() fieldName: string = ''; // 档案类型
  @Input() fileNum: number = 1; // 文件数量

  @Input() title: string = '上传文件';
  @Input() subTitle: string = '';
  @Input() downLoad: any = {}
  @Input() popInfo: string = '上传相关文件';

  @Input() errMsg: string = ''
  infoMsg = ''

  @Input() groupForm: FormGroup | undefined
  // @Input() uploadUrl: string = '/api/gsxmcp/pb/fm/v1.0/uploadFiles';
  @Output() uploadBack = new EventEmitter();

  @Input() eCertificateObj: any;
  @Output() eCertificateBack = new EventEmitter()

  @Input() isBusinessBill = false

  constructor(
    private uploadService: UploadService,
    private message: MessageService
  ) { }

  uploadedFiles: UploadedFileData[] = []
  @Input() previewIdStr: string = '' // 传入的
  previewIds: string[] = []
  ngOnInit(): void {
    console.log(this.title)
  }
  ngOnChanges(changes: SimpleChanges): void {
    if(changes['previewIdStr']?.currentValue && changes['previewIdStr']?.firstChange){
      let previewIds = changes['previewIdStr'].currentValue.split(',')
      previewIds =previewIds.map((item: string) => {
        return item.split(':')[0]
      })
      this.previewIds = previewIds
    }
  }

  beforeUpload = (file: NzUploadFile): boolean => {
    if(this._beforeUpload(file)){
      this.upload(file)
    }
    return false;
  };
  _beforeUpload = (file: NzUploadFile) => {
    console.log(file)
    const allowType = this.mediaType.find(_ =>  file.type?.indexOf(_) && file.type?.indexOf(_) > -1)
    if(!allowType){
      this.message.error('不允许的文件类型')
      return false
    }

    if(this.uploadedFiles.length >= this.fileNum){
      this.message.error('上传文件数量超过最大限制:' + this.fileNum)
      return false
    }

    return true
  }
  
  upload(file: any){
    const formData = new FormData()
    const fieldType = Object.values(FILE_TYPE).find(value => this.title.indexOf(value) > -1)
    const ufType = fieldType ? fieldType : this.title

    formData.append('file', file)
    formData.append('su', 'pb')
    formData.append('bo', 'fc')
    formData.append('fileType', ufType)
    // var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
    formData.append('suffix', 'png')
    console.log('isBusinessBill: ' + this.isBusinessBill)
    console.log(file)
    // let file = new File(file) // this could be from file input or other source
    
    // let fileReader = new FileReader();

    

    // fileReader.readAsArrayBuffer(file);
    // fileReader.onload = (ev: any) => {
    //   const result = ev.target.result;
    //   console.log('result', result); // here it is
    // }
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e: any) => {
      console.log(e.target.result);
      
      const param = {
        file: e.target.result.split(',')[1],
        // file: e.target.result,
        su: 'pb',
        bo: 'fc',
        fileType: ufType,
        suffix: file.name.substring(file.name.lastIndexOf('.') + 1)
      }
      this.uploadService._upload(param, this.isBusinessBill).subscribe({
        next: (res) => {
          console.log(res)
          this.uploadedFiles.push(res)
          this.uploadBack.emit(this.getUploadBackStr())
        },
        error: () => {
          this.message.error('文件上传失败, 请稍后再试')
        }
      })
    };

    return

    this.uploadService._upload(formData, this.isBusinessBill).subscribe({
      next: (res) => {
        console.log(res)
        this.uploadedFiles.push(res)
        this.uploadBack.emit(this.getUploadBackStr())
      },
      error: () => {
        this.message.error('文件上传失败, 请稍后再试')
      }
    })
  }

  fileToBase64Async(file: any) {
    
  }

  nzFilesChange(file: any){
    console.log(file)
  }

  //#region 电子证照验证
  certificateLoading = false
  async eCertificate(){
    console.log(this.eCertificateObj)
    // 先实名认证
    // this.goRealName()
    // return

    const valueKey = this.eCertificateObj[0]?.['filter']?.['data']?.['filter'][0]?.['value']?.replace('Model.', '')
    if(!valueKey){
      this.message.error('电子证照验证失败, 请检查对应的证件号')
      return
    }
    if(!this.groupForm?.get(valueKey)?.value){
      this.message.error('电子证照验证失败, 请输入对应的证件号')
      return
    }
    // {"result":"NJOUB59P:9","info":[{"authCode":"20230405175503089NC023243509_4401002022000B0WQR","type":"营业执照（广州）","cardNo":"4401002022000B0WQR","fileId":"NJOUB59P:9"}]}
    try{
      this.certificateLoading = true
      const license = await firstValueFrom(this.uploadService._getLicensePdf(this.groupForm?.get(valueKey)?.value))
      if(license && license.result){
        this.groupForm?.get(this.fieldKey)?.setValue(license.result)
        this.groupForm?.get(valueKey)?.disable()
        this.uploadAvailable = false
        this.infoMsg = '电子证照验证通过,当前文件不需上传'
        this.uploadBack.emit(license.result)
      }else{
        this.message.info('电子证照验证失败，请重试')
      }
      this.certificateLoading = false
    }catch(error: any){
      this.message.createErrorMessage(error)
      this.certificateLoading = false
    }
  }
  goRealName(){
    console.log(this.setId)
    const redirect_uri = `https://service.gzwatersupply.com/apps/gsxmcp/gsxm-project/index.html?dyAuthFormId=${this.setId}`

    const url = `https://tyrz.gd.gov.cn/tif/sso/connect/page/oauth2/authorize?service=initSerivice&response_type=code&client_id=tyrz_gzzxzls&scope=all&redirect_uri=https://www.gzzcwatersupply.com/apps/gsxmcp/zengc/index.html?dyAuthFormId=${this.setId}&type=1`

    window.open(url, '_self');
  }
  //#region 

  // 上传文件返回的字符串 id
  getUploadBackStr(){
    return this.uploadedFiles.map(item => {
      if(this.previewIds.indexOf(item.fileId) === -1){
        this.previewIds.push(item.fileId)
      }
      const id = item.fileId + ':0'
      return id
    }).join(',')
  }

  // 删除图片
  deleteImg(fileId: string){
    this.previewIds = this.previewIds.filter(id => {
      return id.indexOf(fileId) === -1
    })
    this.uploadedFiles = this.uploadedFiles.filter(item => {
      return item.fileId.indexOf(fileId) === -1
    })
    this.uploadBack.emit(this.getUploadBackStr())
  }

}
